<template>
  <div class="revenueExpenditureDetails">
    <h3>收支明细</h3>
    <div class="line"></div>

    <div class="operate">
      <el-form ref="ruleFormRef" :model="queryChangeRecord" label-width="120px" class="demo-ruleForm" :inline="true">
        <el-form-item label="交易时间" prop="date">
          <el-date-picker v-model="queryChangeRecord.date" @focus="dateLimt.handleFocus"
            @calendar-change="dateLimt.handleChange" :disabled-date="dateLimt.disabledDate" type="daterange"
            start-placeholder="开始日期" end-placeholder="结束日期" :range-separator="'到'" />
        </el-form-item>
        <el-form-item label="订单号" prop="name">
          <el-input v-model="queryChangeRecord.orderId" style="width: 320px" placeholder="请输入订单号搜索"
            :prefix-icon="Search" />
        </el-form-item>
        <el-form-item label="账单类型" prop="billType">
          <el-select v-model="queryChangeRecord.billType" placeholder="请选择账单类型" multiple style="width: 100%">
            <el-option v-for="item in billTypeData" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="计费模式" prop="chargeMode">
          <el-select v-model="queryChangeRecord.chargeMode" placeholder="请选择计费模式" multiple style="width: 100%">
            <el-option v-for="item in chargeMode" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账期" prop="billCycle">
          <el-date-picker v-model="queryChangeRecord.billCycle" type="month" placeholder="请选择账期" value-format="YYYY_MM"
            :clearable="false" :disabled-date="billCycleDisable" style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            查询
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="icon">
        <SvgIcon icon="refresh" class-name="icon-self" @click="getList"></SvgIcon>
        <SvgIcon icon="download" class-name="icon-self"></SvgIcon>
      </div>
    </div>

    <div class="data">
      <el-table :data="tableData" style="width: 100%; margin-top: 30px">
        <el-table-column prop="tradeTime" label="交易时间" :formatter="timeFormat" width="170" />
        <el-table-column prop="orderId" label="交易号/订单号" width="120" />
        <el-table-column prop="billType" label="账单类型" :formatter="billTypeFormat" width="150" />
        <el-table-column prop="serviceTypeName" label="云服务名称" width="180" />
        <el-table-column prop="resourceTypeName" label="资源名称" width="180" />
        <el-table-column prop="chargeMode" label="计费模式" :formatter="chargeModeFormat" />
        <el-table-column prop="effectiveTime" label="消费时间" width="170">
          <template v-slot:default="scope">
            <div>{{ timeFormathms(scope.row.effectiveTime) }} </div>
            <div>{{ timeFormathms(scope.row.expireTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="regionName" label="区域名称" width="120" />
        <el-table-column prop="officialAmount" label="官网价（元）" :formatter="moneyFormat" width="120" />
        <el-table-column prop="couponAmount" label="优惠金额（元）" :formatter="moneyFormat" width="130" />
        <el-table-column prop="eraseAmount" label="抹零金额（元）" :formatter="moneyFormat" width="130" />
        <el-table-column prop="consumeAmount" label="应付金额（元）" :formatter="moneyFormat" width="130" />
        <el-table-column prop="billStatus" label="账单状态" :formatter="billStatusFormat" />
      </el-table>
      <el-pagination :hide-on-single-page="true" background :current-page="queryChangeRecord.page"
        :page-size="queryChangeRecord.pageSize" :page-sizes="[5, 10, 20, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="queryChangeRecord.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { QueryParams } from '@/types/public'
import { numberToCurrencyNo } from '@/utils'
import { Search } from '@element-plus/icons-vue'
import { billStatusData, billTypeData, chargeMode } from './data'
import { timeFormat, timeFormathms } from '@/utils/formatter'
import rechageService from '@/api/voucherCenter/rechageService'
import { FormInstance } from 'element-plus'
import dateLimt from '@/utils'

const searchKey = ref('')
const ruleFormRef = ref<FormInstance>()

interface QueryChangeRecord extends QueryParams {
  userId: string
  total?: number
  billCycle: string,
  chargeMode?: Array<number>,
  orderId?: string
  date?: string
  billType?: Array<number>
  tradeTimeBegin?: number
  tradeTimeEnd?: number
}

let tableData: Array<QueryChangeRecord> = reactive([])
const queryChangeRecord = reactive<QueryChangeRecord>({
  page: 1,
  pageSize: 10,
  total: 0,
  userId: localStorage.getItem('userId') as string,
  billCycle: new Date().getFullYear() + '_' + ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : '0' + (new Date().getMonth() + 1))
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      getList()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getList()
}

const moneyFormat = function (row: any, column: any, cellValue: any, index: any) {
  return '￥' + numberToCurrencyNo(cellValue)
}

const billTypeFormat = function (row: any, column: any, cellValue: any, index: any) {
  return billTypeData.filter(item => {
    return item.value == cellValue
  })[0].text
}
const chargeModeFormat = function (row: any, column: any, cellValue: any, index: any) {
  return chargeMode.filter(item => {
    return item.id === cellValue
  })[0].text
}
const billStatusFormat = function (row: any, column: any, cellValue: any, index: any) {
  return billStatusData.filter(item => {
    return item.value === cellValue
  })[0].text
}
const getList = () => {
  if (queryChangeRecord.date) {
    queryChangeRecord.tradeTimeBegin = new Date(queryChangeRecord.date[0]).getTime()
    queryChangeRecord.tradeTimeEnd = new Date(queryChangeRecord.date[1]).getTime()
  } else {
    delete queryChangeRecord.tradeTimeBegin
    delete queryChangeRecord.tradeTimeEnd
  }
  rechageService.billQuery(queryChangeRecord).then(res => {
    tableData.length = 0
    tableData.push(...res.data.data.billInfo)
    queryChangeRecord.total = res.data.data.totalCount
  })
}

getList()
const handleSizeChange = (val: number) => {
  queryChangeRecord.page = 1
  queryChangeRecord.pageSize = val
  getList()
}
const handleCurrentChange = (val: number) => {
  queryChangeRecord.page = val
  getList()
}
const billCycleDisable = (time: number) => {
  return time > new Date().getTime()
}
</script>

<style lang="scss">
.revenueExpenditureDetails {
  background-color: #fff;
  padding: 30px;

  .el-form-item__content {
    width: 300px;
  }

  .line {
    margin: 20px 0;
    border-top: 1px solid #e7e9ef;
  }

  .operate {
    display: flex;
    position: relative;

    .filter-time {
      position: absolute;
      display: flex;
      align-items: center;
      left: 400px;

      span {
        margin-right: 10px;
      }
    }

    .icon {
      position: absolute;
      display: flex;
      align-items: center;
      right: 0;
      color: #aaaebf;

      .icon-self {
        cursor: pointer;
      }

      .icon-self+.icon-self {
        margin-left: 10px;
      }
    }
  }
}
</style>
